
// 数据缓存
export const cache = {
  data: {},
  set(key, data, memory = false, expire) {
    try {
      if (expire) {
        expire = new Date().getTime() + expire * 1000;
      }
      const _data = {
        expire,
        data,
      };

      if (!memory) {
        window.sessionStorage.setItem(key, JSON.stringify(_data));
      } else {
        this.data[key] = _data;
      }
      return true;
    } catch (e) {
      console.error(e);
      return false;
    }
  },
  get(key, memory = false) {
    try {
      if (!memory) {
        const dataString = window.sessionStorage.getItem(key);
        if (!dataString) return null;

        const cached = JSON.parse(dataString);
        if (cached.expire && cached.expire < new Date().getTime()) {
          window.sessionStorage.removeItem(key);
          return null;
        }
        return cached.data;
      } else {
        const _data = this.data[key];
        if (!_data || (_data.expire && _data.expire < new Date().getTime())) {
          this.data[key] = undefined;
          return null;
        }
        return _data.data;
      }
    } catch (e) {
      console.error(e);
      return null;
    }
  },
  clear(key, memory = false) {
    try {
      if (memory) {
        delete this.data[key];
      } else {
        window.sessionStorage.removeItem(key);
      }
      return true;
    } catch (e) {
      console.error(e);
      return false;
    }
  }
}
